<?php

function weekNumberToDateRange($week_number , $month , $year){

    $f_day  = _get_first_day_of_month("$year-$month-01");
    $f_week_length = _get_first_week_length($f_day);
    $target_week_first_day = $f_week_length + ($week_number - 1) * 7;
    $target_week_last_day = $target_week_first_day + 7;

    $date_from = _get_real_date( $year , $month , $target_week_first_day , $deacrease_by = 7);
    $date_to = _get_real_date( $year ,$month , $target_week_last_day   );

    return array($date_from , $date_to);
}

function dateRangeToWeekNumber($rang_arr){
    $first_date      = $rang_arr[0];
    $first_date_time = strtotime($first_date);

    $month = date('m',$first_date_time);
    $year = date('Y',$first_date_time);
    $source_day = date('d',$first_date_time);


    $f_day  = _get_first_day_of_month("$year-$month-01");
    $f_week_length = _get_first_week_length($f_day);

    $cul = $source_day - $f_week_length;
    $num_of_weeks = $cul/7;
    return $num_of_weeks + 1;
    //return
}

function _get_real_date($year ,$month , $day  , $deacrease_by = 1){
    $max_loop = 14;
    $month = sprintf('%02d', $month);
    $date = "$year-$month-$day";
    while ( !($time = strtotime($date)) ) {
        if(--$max_loop == 0 )break;//break any way to avoide infinte loop in case
        $day -= $deacrease_by ;
        $date = "$year-$month-$day";
    }
    return $date;


}
function _get_first_day_of_month($date){

    $time =  strtotime($date);
    return date( 'D' , $time );

}

function _get_first_week_length($day){


    switch ($day) {
        case 'Sat':
            $ret = 7;
            break;
        case 'Sun':
            $ret = 6;
            break;
        case 'Mon':
            $ret = 5;
            break;
        case 'Tue':
            $ret = 4;
            break;
        case 'Wed':
            $ret = 3;
            break;
        case 'Thu':
            $ret = 2;
            break;
        case 'Fri':
            $ret = 1;
            break;
        default:
            $ret = 0;
            break;
    }
    return $ret;
}

